import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;


public class MessageSender implements Runnable {

	protected boolean running = true;
	protected ArrayList<String> messages = new ArrayList<String>();


	private static MessageSender instance = new MessageSender();
	public static MessageSender getInstance()
	{
		return instance;
	}
	private MessageSender() {
	}

	public void stop() {
		running = false;
	}

	/**
	 * Add message for sending.
	 */
	 public void send(String user, String message) {
		 System.out.println("in senddddd");
		 synchronized (messages) {
			 messages.add("[" + user + "]: " + message);
			 System.out.println("send" + message);
			 messages.notify();
		 }
	 }

	 public void run() {

		 while (running) {

			 if (messages.size() == 0) {
				 try {
					 synchronized (messages) {
						 messages.wait();
					 }
				 } catch (InterruptedException e) {
					 // Ignore
				 }
			 }
/*
			 synchronized (ConnectionsHolder.getInstance().connections) {
				 String[] pendingMessages = null;
				 synchronized (messages) {
					 pendingMessages = messages.toArray(new String[0]);
					 messages.clear();
				 }
				 System.out.println("yap really will send now");
				 // Send any pending message on all the open connections
				 for (int i = 0; i < ConnectionsHolder.getInstance().connections.size(); i++) {
					 PrintWriter writer;
					try {
						System.out.println("okkk");
						writer = ConnectionsHolder.getInstance().connections.get(i).getWriter();
					writer.print("yesssssssssss");
						System.out.println("ahhhahaha");
					/* for (int j = 0; j < pendingMessages.length; j++) {
						 writer.println(pendingMessages[j] + "<br>");
						 System.out.println("send to use" + pendingMessages[j]);
					 }*/
			/*		writer.flush();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					 
				 }
			 }
*/
		 }

	 }

}

